package com.shenhan.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author shenhan
 * @create 2020/6/10 14:30
 * @description Condition实现精准通知和唤醒线程
 * target: A调用结束，调用B然后调用C再调用A
 */
public class C {
    public static void main(String[] args) {
        Data3 data = new Data3();
        new Thread(()-> {
            for (int i = 0; i < 3; i++) {
                data.printA();
            }
        }, "A").start();
        new Thread(()-> {
            for (int i = 0; i < 3; i++) {
                data.printB();
            }
        }, "B").start();
        new Thread(()-> {
            for (int i = 0; i < 3; i++) {
                data.printC();
            }
        }, "C").start();
    }
}

class Data3 {
    // 1A 2B 3C
    private int number = 1;
    private final Lock lock = new ReentrantLock();
    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();
    Condition conditionC = lock.newCondition();

    public void printA() {
        lock.lock();
        try {
            while (number != 1) {
                conditionA.await();
            }
            System.out.println("AAA");
            number++;
            conditionB.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            while (number != 2) {
                conditionB.await();
            }
            System.out.println("BBB");
            number++;
            conditionC.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            while (number != 3) {
                conditionC.await();
            }
            System.out.println("CCC");
            number = 1;
            conditionA.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
